<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { ref } from 'vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { useGuessList } from '@/composables'
//获取首页轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerdata = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
//获取首页分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
const isLoading = ref(false)
//获取分类数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerdata(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
const { guessRef, onScrolltolower } = useGuessList()
const isTriggered = ref(false)
const onRefresherrefresh = async () => {
  //开始动画
  isTriggered.value = true
  // await getHomeBannerdata()
  // await getHomeCategoryData()
  // await getHomeHotData()
  guessRef.value?.resetData()
  //优化等待所有的请求完成后
  await Promise.all([
    getHomeBannerdata(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  //关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 顶部 -->
  <CustomNavbar></CustomNavbar>
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    scroll-y
    :refresher-triggered="isTriggered"
    class="sc-1"
    @scrolltolower="onScrolltolower"
  >
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 轮播 -->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!-- 分类 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 推荐专区 -->
      <HotPanel :list="hotList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.sc-1 {
  flex: 1;
}
</style>
